<?php
//debug($this->data);
//debug(json_encode($adjectivelist)); 
//debug($synonymlist);
?>

<?php
echo $javascript->link(array('autocomplete/jquery.tokeninput', 'tag-option/jquery.optionTree', 'front/jquery-ui-1.8.16.custom.min'));
echo $this->Html->css(array('autocomplete/token-input-facebook', 'autocomplete/token-input', 'slider/jquery-ui-1.8.16.custom'));
?>
<style type="text/css">
    select.vertical {
        display: block;
    }

</style>
<script type="text/javascript">
    $(function() {

        var options = {
            empty_value:null,
            indexed: true,  // the data in tree is indexed by values (ids), not by labels
            on_each_change: 'tags', // this file will be called with 'id' parameter, JSON data must be returned
            choose: function(level) {
                return 'Choose level ' + level;
            },
            loading_image: '<?php echo $this->base . "/app/webroot/img/ajax-load.gif"; ?>',
            show_multiple: false, // if true - will set the size to show all options
            choose: '' // no choose item
        };

        var displayParents = function() {
            var labels = []; // initialize array
            $(this).siblings('select') // find all select
            .find(':selected') // and their current options
            .each(function() { labels.push($(this).text()); }); // and add option text to array
            // $("<div >").html( labels.join(' > ')+"<a class='delete' href='#'> X</a>").appendTo('#demo7-result');  // and display the labels
            if($(this).find(':selected').value!='0'){
                $('#demo7-result').css("background-color","#BAF598");
                $('#demo7-result').css("border","1px solid");
                 
                $('#demo7-result').html($('<div class="tag_name">').text( labels.join(' > ')));  // and display the labels
            }
        }
  
        $.getJSON('tags?id=2', function(tree) { // initialize the tree by loading the file first
            $('input[id=demo7]').optionTree(tree, options).change(displayParents);
        
        
        });
        
        /*****************This event is called to add tags to the system. This will copy the content of
         * #demo7-result to #tagpool and also will append a hidden field with tagId of the selected tag.
         *  After the tag is added select will be reloaded  *******************************************/
       
        $('#more ').click(function(){
            //alert($('input[name^="data[Attribute]"]').length);
            //alert($('#demo7').length);
            if($("#demo7-result").is(':parent')){
                $('#tagpool').append('<div id="'+$('input[id=demo7]').val()+'"class="new_tag_container">'+$('#demo7-result').html()+"<div class='remove_tag'>X</div><div class='clearfix'></div><div class='edit_tag'>Edit</div><input type='hidden' name='tag_ids[]' value='"+$('input[id=demo7]').val()+"'/>");
                $('#tagpool').append($('#attributes').html());
                $(".new_tag_container").removeClass("new_tag_container").addClass("tag_container");
                $(".tagwrapper").css("background","#EDFFED");
                $(".tagwrapper").css("border","1px solid #999");
                $("#attributes").empty();
                $("#demo7-result").empty();
                $('#demo7-result').css("background-color","");
                $('#demo7-result').css("border","none");
                $.getJSON('tags?id=2', function(tree) { // initialize the tree by loading the file first
                    $('input[id=demo7]').optionTree(tree, options).change(displayParents);
        
        
                });
            }else{
                alert('Please Select one tag to add.');
            }
        });
         
             
                
        /*************** This will remove the tag**********************/       
             
        $(".remove_tag").live('click',function(){
            //alert('afa');
            //alert($($($(this).prev()).parent()).attr("id"));
            var currentID=$($(this).parent()).attr("id");
            //alert(currentID);
            $('#'+currentID).remove();
            
             
        });
        
        /********************************* Tag remove ends    *******************************/
       
       
        /*********************** Edit tag chain   **********************/
       
        $(".edit_tag").live('click',function(){
            //alert($($($(this).prev()).parent()).attr("id"));
            var currentID=$($(this).parent()).attr("id");
            //alert($('#'+currentID).remove().html());
            $('#demo7-result').append($('#'+currentID).remove().html());
            //$('#'+currentID).remove();
            var parent_ids='';
            
            $.ajax({
                url: "tag",
                global: false,
                type: "POST",
                data: {id : currentID },
                dataType: "html",
                async:false,
                success: function(response){
                    x=response;
                           
                }
            }
        );
            //alert(currentID);  
            var t=x.split(',');
            var options = {
                empty_value: 'null',
                indexed: true,  // the data in tree is indexed by values (ids), not by labels
                on_each_change: 'tags', // this file will be called with 'id' parameter, JSON data must be returned
                choose:'',
                preselect: {'data[Subject][tag_ids]':t}
            };

            var displayParents = function() {
                var labels = []; // initialize array
                $(this).siblings('select') // find all select
                .find(':selected') // and their current options
                .each(function() { labels.push($(this).text()); }); // and add option text to array
                $('<div>').text(this.value + ':' + labels.join(' > ')).appendTo('#demo5-result');  // and display the labels
            }

            $.getJSON('tags', function(tree) { // initialize the tree by loading the file first
                $('#demo7').optionTree(tree, options).change(displayParents);
                
            });
            var checkpool=$('#tagpool').html();
            if($.trim(checkpool)!=''){
                $(".tagwrapper").css("background","#EDFFED");
                $(".tagwrapper").css("border","1px solid #999");
            }else{
                $(".tagwrapper").css("background","");
                $(".tagwrapper").css("border","");
            }
            
        });
        
        
        /*********************Edit Tag ends**********************/
   
    });

    $(document).ready(function(){
        var checkpool=$('#tagpool').html();
        if($.trim(checkpool)!=''){
            $(".tagwrapper").css("background","#EDFFED");
            $(".tagwrapper").css("border","1px solid #999");
        }else{
            $(".tagwrapper").css("background","");
            $(".tagwrapper").css("border","");
        }

    });
  
</script>

<script>
    $(document).ready(function(){
         
    });
</script>
<table id="table" width="900px" cellpadding="5" cellspacing="5">
    <tr align="center"><td>

            <?php echo $this->Form->Create('Subject', array('enctype' => 'multipart/form-data')); ?>
            <table  cellpadding="0" cellspacing="0" >



                <?php echo $this->Form->input('id', array('type' => 'hidden')); ?>
                <tr>
                    <td id="label">Subject</td>
                    <td><?php echo $this->Form->input('Subject.subject', array('label' => '', 'id' => 'title')); ?><div id="error" style="color:red; font-size: 14px;margin: 3px 0 0 446px;"></div></td>

                <script type="text/javascript">
                
                    $(document).ready(function() {
                        $("#title").tokenInput("<?php echo $this->base; ?>/admin/Subjects/synonyms",{
                            theme: "facebook",
                            preventDuplicates: true,
                            queryParam: "search",
                            searchDelay: 400,
                            tokenLimit: 1,
                            minChars: 2,
                            
                            prePopulate: <?php
                if (isset($subjecttitle)) {
                    echo $subjecttitle;
                }
                ?>
                    });
                                    
                                    
                });
                </script>
    </tr>                
    <tr>
        <td id="label" >Specifier</td>
        <td><?php echo $this->Form->input('Subject.desc', array('label' => '', 'type' => 'text')); ?></td>
    </tr>
    <tr>
        <td id="label"  >Synonyms</td>
        <td><div id="redirect-div">

            </div>
            <?php
            //echo $this->Form->input('synonyms',array('label'=>'','size'=>'42'));
            echo $this->Form->input('redirects', array('label' => '', 'type' => 'textarea', 'cols' => '56', 'rows' => '10', 'id' => 'redirect', ''));
            ?>* In CSV(e.g Happy,Jolly) formate</td>
    </tr>
    <tr><td>&nbsp;</td><td><div id="tagpool" class="tagwrapper">
                <?php
                $i = '0';
                if (isset($this->data['Subject']['taglist'])) {
                    foreach ($this->data['Subject']['taglist'] as $tag) {
                        if (!empty($tag['tag_id'])) {
                            echo "<div id=" . $tag['tag_id'] . " class='tag_container'><div class='tag_name'>" . $tag['tag'] . "</div><div class='remove_tag'>X</div><div class='clearfix'></div><div class='edit_tag'>Edit</div>
                                <input type='hidden' name='tag_ids[]' value='" . $tag['tag_id'] . "'/>
                                </div>";
                            if (isset($this->data['Attribute'])) {
                                foreach ($this->data['Attribute'] as $value) {
                                    if ($value['tag_id'] == $tag['tag_id']) {
                                        echo $this->Form->input('Attribute.' . $i . '.id', array('type' => 'hidden', 'value' => $value['id']));
                                        echo $this->Form->input('Attribute.' . $i . '.subject_id', array('type' => 'hidden', 'value' => $value['subject_id']));
                                        echo $this->Form->input('Attribute.' . $i . '.attribute', array('type' => 'hidden', 'value' => $value['attribute']));
                                        echo $this->Form->input('Attribute.' . $i . '.value', array('label' => $value['attribute'], 'value' => $value['value']));
                                        $i++;
                                    }
                                }
                            }
                        }
                    }
                }
                ?>
            </div></td></tr>
    <tr>
        <td id="label" >Tag</td>
        <td style="margin-right: 20px;"><div><?php echo $this->Form->input('Subject.tag_ids', array('label' => '', 'id' => 'demo7', 'type' => 'hidden')); ?><span id="more" class="mybutton"><a href="#">Save</a></span><div id="error-message" class="error-message"></div><div id="tag_values"></div></div>
            <div class="results" id="demo7-result"></div><div id="hidden_val"></div>
            <div id="attributes"></div>
        </td>
    </tr>
    <?php if (!empty($this->data['Subject']['image'])) { ?>
    <?php echo $this->Form->input('imagename', array('type' => 'hidden', 'value' => $this->data['Subject']['image'])); ?>
        <tr style="vertical-align: top;">
            <td id="label" >Image</td>
            <td>
                <?php
                $thumbnail = $this->PhpThumb->generate(
                        array(
                            'save_path' => WWW_ROOT . 'img/uploads/Subjects/thumbs',
                            'display_path' => 'uploads/Subjects/thumbs',
                            'error_image_path' => 'img/error.jpg',
                            'src' => WWW_ROOT . "img/uploads/Subjects/" . $this->data['Subject']['image'],
                            'w' => 200,
                            'h' => 200,
                            'q' => 100,
                            'zc' => 1
                        )
                );

                echo $this->Html->image($thumbnail['src'], array('width' => $thumbnail['w'], 'height' => $thumbnail['h']));
                ?>
                <div style="color:#c73e14;"><?php echo $this->Html->link("Delete image?", array('controller' => 'Subjects', 'action' => 'delete_image', $this->data['Subject']['id']), array('style' => 'color:#c73e14;')); ?></div>
            </td>
        </tr>
    <?php } else { ?>
        <tr>
            <td id="label">Image</td>
            <td><?php echo $this->Form->input('Subject.image', array('label' => '', 'type' => 'file', 'id' => 'image')); ?><div id="missing_image" class="error-message"></div></td>
        </tr>      
    <?php } ?>
    <tr>
        <td id="label">Adjectives</td>
        <td><div><?php
        echo $this->Form->input('Subject.old_adjectives',array('type'=>'hidden','value'=>$this->data['adjective_ids']));
        echo $this->Form->input('Subject.adjective_ids', array('label' => '', 'id' => 'demo-input-facebook-theme')); ?>   

                <script type="text/javascript">
                    $(document).ready(function() {
                        $("#demo-input-facebook-theme").tokenInput("<?php echo $this->base; ?>/admin/Subjects/adjectives", {
                            theme: "facebook",
                            preventDuplicates: true,
                            tokenLimit: 3,
                            queryParam: "q",
                            prePopulate: <?php
    if (isset($adjectivelist)) {
        echo json_encode($adjectivelist);
    } else {
        echo "[]";
    }
    ?>
                            
            });
        });
                </script>
            </div>
        </td>
    </tr> 
    <tr>
        <td id="label">17+ &nbsp;&nbsp;&nbsp;?</td>
        <td><?php echo $this->Form->input('17+', array('label' => '', 'type' => 'checkbox')); ?></td>
    </tr>
    <?php
    if (!$this->Access->check('User', 'update')) {
        if ($this->data['Subject']['user_id'] == $_SESSION['Auth']['User']['id'] && $this->data['Subject']['status'] == '0') {
            if (isset($this->data['SubjectRate'])) {
                $rating = $this->data['SubjectRate']['0']['rating'];
            } else {
                $rating = '0';
            }
            ?><tr>
                <td>Rate It</td>
                <td>
                    <div class="meter-div">
                        <!-- Slider -->
                        <input type="hidden" id="rating_id" value="<?php echo $this->data['SubjectRate']['0']['id']; ?>" name="rating_id" style="border:0; color:#f6931f; font-weight:bold;" />
                        <input type="hidden" id="rating_val" value="<?php echo $rating; ?>" name="rating" style="border:0; color:#f6931f; font-weight:bold;" />
                        <div id="slider-range-min" style="width:500px;"> </div>
                    </div>
                </td>
            </tr>
        <?php }
    } ?>
    <tr><td colspan="2">&nbsp;</td></tr>
    <tr><td></td><td></td></tr>
    <tr>
        <td></td>
    </tr>
</table><?php
    echo $this->Form->input('status', array('type' => 'hidden'));
    echo $this->Form->end(array('label' => 'Update', 'class' => 'mybutton'));
    ?>
</td></tr>
</table>
<script language="javascript">
    $(document).ready(function() {
        $( "#slider-range-min" ).slider({
            range: "min",
            value: $('input[name=rating]').val(),
            min: 0,
            max: 100,
            slide: function( event, ui ) {
                            
                $( ".ui-slider-handle" ).text( ui.value );
				
                //add color class
                if(ui.value<='25'){
                    $( ".ui-slider-handle" ).addClass('low_value');
                }else if(ui.value<='50'){
                    $( ".ui-slider-handle" ).addClass('medium_value');
                }
				
            }
        });
        $( ".ui-slider-handle" ).text($( "#slider-range-min" ).slider( "value" ) );
        //add color class
        if('ui.value'<='25' ){
            $( ".ui-slider-handle" ).addClass('low_value');
                                      
        }else if('ui.value'<='50'){
            $( ".ui-slider-handle" ).addClass('medium_value');
        }
				  
    });
    $('#SubjectAdminEditForm').live('submit',function(){
        var error='0';
        
        if($('#image').val()==''){
            $('#missing_image').fadeIn(100);
            $('#missing_image').text('Upload an Image first.').delay(5000).fadeOut(900);
            error=1;
        }
        
        
        $('input[name=rating]').val($( "#slider-range-min" ).slider( "value" ));
        if( $('#title').val()==''){
            $('#error').fadeIn(100);
            $('#error').text('Required').delay(5000).fadeOut(900);
            
            error=1;

        }
        
        if( $('#tagpool').text()==''){
            $('#error-message').fadeIn(100);
            $('#error-message').text('Add atleast one tag to the Subject').delay(5000).fadeOut(900);
            error=1;
            

        }
        if($('input[name=rating]').val()=='0'){
            if(confirm('Are you sure you want to rate this subject a 0 ?')){
                return true;
            }else{
                return false;        
            }
        }
        if(error=='1'){
            return false;
        }
    });
</script>
